package filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter", urlPatterns = {"/Home", "/Guess", "/Rank"})
public class LoginFilter implements Filter {
    private FilterConfig fc;
    public void init(FilterConfig config) throws ServletException {
        fc = config;
    }

    public void destroy() {}

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        if (checkCookie(httpRequest)) {
            chain.doFilter(request, response);
            return;
        }

        HttpSession session = httpRequest.getSession();
        String lastUser = (String) session.getAttribute("user");
        if (lastUser == null) {
            RequestDispatcher view = httpRequest.getRequestDispatcher("login.jsp");
            view.forward(httpRequest, httpResponse);
        }else
            chain.doFilter(request, response);
    }

    private boolean checkCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("user".equals(cookie.getName()) && !cookie.getValue().isEmpty()) {
                    return true;
                }
            }
        }
        return false;
    }
}
